<template>
  <div>
    <div class="search">
      <input v-model="keyword" placeholder="请输入城市名或拼音" />
    </div>
    <div class="content" v-show="keyword" ref="search">
      <ul>
        <li v-for="item of list" :key="item.id" @click="cityclick(item.name)">
          {{ item.name }}
        </li>
        <li v-show="hasnodata">没有搜索到符合要求的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import bscroll from "better-scroll";
export default {
  name: "CitySearch",
  props: {
    cities: Object,
  },
  data() {
    return {
      keyword: "",
      list: [],
    };
  },
  methods: {
    cityclick(newcity) {
      // this.$store.commit('changecity', newcity)
      this.changecity(newcity);
      this.$router.push("/");
    },
    ...mapMutations(["changecity"]),
  },
  watch: {
    keyword() {
      if (!this.keyword) {
        this.list = [];
        return;
      }
      const result = [];
      for (let i in this.cities) {
        this.cities[i].forEach((value) => {
          if (
            value.spell.indexOf(this.keyword) > -1 ||
            value.name.indexOf(this.keyword) > -1
          ) {
            result.push(value);
          }
        });
        this.list = result;
      }
    },
  },
  computed: {
    hasnodata() {
      return !this.list.length;
    },
  },
  updated() {
    this.scroll = new bscroll(this.$refs.search);
  },
};
</script>

<style scoped>
.search {
  padding: 0.1rem 0.1rem 0;
  height: 0.72rem;
  line-height: 0.72ewm;
  background: #00bcd4;
}
input {
  padding: 0 0.1rem;
  width: 100%;
  height: 0.62rem;
  text-align: center;
  box-sizing: border-box;
  color: #666;
  border-radius: 0.08rem;
}
.content {
  overflow: hidden;
  position: absolute;
  top: 1.68rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;
  z-index: 1;
}
li {
  padding-left: 0.2rem;
  line-height: 0.6rem;
  background: #fff;
}
</style>